<template>
    <div class="full-percent">
        <div style="display: flex;">
            <div style="width: 150px;text-align: right;padding-right: 10px;line-height: 32px;">
                Reader数据库
            </div>
            <div style="padding-right: 5px;width: calc((80% - 400px)/2);">
                <el-select v-model="etlConfig.dbType" placeholder="请选择数据库" @change="clearDB" class="input-auto-resize">
                    <el-option v-for="item in dbTypes" :key="item" :label="item" :value="item" />
                </el-select>
            </div>
            <div style="padding-right: 5px;width: calc((80% -  400px)/2);">
                <el-select v-model="etlConfig.dbSequence" placeholder="请选择实例" class="input-auto-resize"
                    @change="clearTable">
                    <el-option v-for="(item, index) in dbNames" :key="index" :label="item.name"
                        :value="item.sequence" />
                </el-select>
            </div>
            <div style="width: 120px;text-align: right;padding-right: 10px;line-height: 32px;">
                Reader匹配表名
            </div>
            <el-input v-model="etlConfig.table" class="font-auto-resize" style="width: 20%;"
                placeholder="为空查询所有有权限的表" />
            <div style="width: 50px;text-align: right;">
                <el-button :icon="getIcon('search')" class="button-auto-resize" @click="searchTable" circle
                    :disabled="!etlConfig.dbSequence" type="primary" />
            </div>
        </div>
        <div class="tables">
            <el-tabs v-model="activeTab" type="border-card" ref="tabRef" class="table-tab"
                v-if="Object.keys(tables).length">
                <el-tab-pane :label="item" :name="`schema_${index}`" v-for="(item, index) in Object.keys(tables)"
                    :key="index">
                    <el-scrollbar class="full-percent">
                        <div v-waterfall>
                            <div v-for="(tableItem, tableItemindex) in tables[item]" :key="tableItemindex"
                                :class="`table-item ${checkSelected(tableItem)}`" @click="selectTable(tableItem)">
                                {{ tableItem.table_name }}
                            </div>

                        </div>
                    </el-scrollbar>
                </el-tab-pane>
            </el-tabs>
            <div v-else class="unselectTable">
                请选择数据库查询配置Reader信息
            </div>
        </div>
    </div>
</template>

<script setup>
import { useTabPaneAnimation, useRequest } from "@usehook"
import { getIcon } from "@/utils/tools"

const props = defineProps({
    db: {
        type: Object,
        required: true,
        default: {}
    },
    dbTypes: {
        type: Array,
        required: true,
        default: []
    }
})

const emit = defineEmits(['change'])

let etlConfig = $ref({})
let tables = $ref([])
let dbNames = $ref([])
let activeTab = $ref("")

useTabPaneAnimation(() => activeTab)

const clearTable = (sequence) => {
    tables = []
    etlConfig.selectTable = []
    activeTab = ""
    etlConfig.dbName = Object.values(props.db).flatMap(e => e).filter(e => e.sequence === sequence)[0]?.name || ""
}

const clearDB = () => {
    etlConfig.dbSequence = ""
    clearTable()
}

const searchTable = () => {
    if (!etlConfig.dbSequence) return
    useRequest({ url: "/data/table/search", loadingMessage: "正在查询数据库获取表信息", loadingTarget: ".console-page", dbSequence: etlConfig.dbSequence, table: etlConfig.table }).then(resp => {
        if (resp && resp.status) {
            tables = resp.data.reduce((acc, item) => {
                const schema = item.table_schema;
                (acc[schema] || (acc[schema] = [])).push(item); // 按 schema 分组
                return acc
            }, {});

            activeTab = "schema_0"
            if (etlConfig.selectTable.length) etlConfig.selectTable = []
        }
    })
}

const checkSelected = (tableItem) => {
    return etlConfig.selectTable.includes(tableItem.table_schema + "." + tableItem.table_name) ? " selected" : ""
}

const selectTable = (tableItem) => {
    if (etlConfig.selectTable.includes(tableItem.table_schema + "." + tableItem.table_name)) {
        etlConfig.selectTable.splice(etlConfig.selectTable.indexOf(tableItem.table_schema + "." + tableItem.table_name), 1)
    } else {
        etlConfig.selectTable.push(tableItem.table_schema + "." + tableItem.table_name)
    }
}

watchEffect(() => {
    dbNames = props.db[etlConfig.dbType]
})

watch(() => etlConfig, (config) => {
    emit("change", config)
}, { deep: true })
</script>